package cn.hpclub.server.model;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.util.InterfaceUtil;

/**
 * 实体类 - 宽带预约
 * 
 */
public class Broadband extends Model<Broadband>{
    private static final Logger   logger           = LoggerFactory.getLogger(Broadband.class);
    private static final long     serialVersionUID = 5108597504836776209L;
    public static final Broadband dao              = new Broadband();
    public static final String    BD_CAMPUS        = "1";                                     // 校园专区数据
    public static final String    BD_MARKET        = "2";                                     // 大市场数据（包括爱家、优家）
    public static final String    BD_SHWDL         = "3";                                     // 商务动力数据
    public static final String    BUSINESS_CODE    = "business_code";
    public static final String    NAME             = "name";
    public static final int       BD_SCOPE_KH      = 1;                                       // 开户
    public static final int       BD_SCOPE_YY      = 2;                                       // 预约

    public boolean update(String sql, String[] ids){
        int updateCount = Db.update(sql, (Object[])ids);
        if(updateCount > 0){
            return true;
        } else{
            return false;
        }
    }

    /**
     * 获取列表
     * 
     * @param pageNumber
     * @param pageSize
     * @param orgId
     * @return
     */
    public Page<Record> getBroadbandList(int pageNumber, int pageSize, int orgId){
        String sqlExceptSelect = "from broadband where is_deleted = 0 and enabled = 1 and broad_type!=2 and broad_type!=3";
        String orgSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and org_id in " + orgSql;
        }

        //// 成都不能看全省的套餐
        Record orgRecord = Db.findFirst("select CityCode from organization where id=?", orgId);
        if(orgRecord != null && (orgRecord.getInt(Organization.CITYCODE) == InterfaceUtil.getIdChengdu())){
            sqlExceptSelect += " and org_id != ?";

            logger.debug("sql = select * " + sqlExceptSelect);
            return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect, InterfaceUtil.getIdTop());
        }

        logger.debug("sql = select * " + sqlExceptSelect);
        return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect);
    }

    /**
     * 获取详情
     * 
     * @param id
     * @return
     */
    public Record getBroadbandById(int id){
        return Db.findById("broadband", id);
    }

    /**
     * 
     * @Title: getBroadbandInfoById
     * @Description:TODO
     * @param bdId
     * @return Broadband
     */
    public Broadband getBroadbandInfoById(int bdId){
        String select = "select b.name as bd_name,b.business_code as bd_code,b.business_summary as bd_summary,(select (select "
                + Organization.DISPLAYNAME + " from " + Constant.Table.ORGANIZATION + " o where o.id=u.org_id) from "
                + Constant.Table.SYS_USER + " u where u.id=b.creator) as bd_creator_org_name from "
                + Constant.Table.BROADBAND + " b where id=?;";

        return dao.findFirst(select, bdId);
    }

    /**
     * @Title: getGovBroadbandList
     * @Description:政企专区获取宽带套餐列表
     * @param pageNumber
     * @param pageSize
     * @param orgId
     * @return Page<Record>
     */
    public Page<Record> getGovBroadbandList(int pageNumber, int pageSize, int orgId){
        String sqlExceptSelect = "from broadband where is_deleted = 0 and enabled = 1 and broad_type=2";
        String orgSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and org_id in " + orgSql;
        }

        // 成都能看全省的套餐
        // Record orgRecord = Db.findFirst("select CityCode from organization
        // where id=?", orgId);
        //
        // if(orgRecord != null && (orgRecord.getInt(Organization.CITYCODE) ==
        // InterfaceUtil.getIdChengdu())){
        // sqlExceptSelect += " and org_id != ?";
        //
        // logger.debug("sql = select * " + sqlExceptSelect);
        // return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect,
        // InterfaceUtil.getIdTop());
        // }

        logger.debug("sql = select * " + sqlExceptSelect);
        return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect);
    }

    public Page<Record> getOpenAcctListByType(int pageNumber, int pageSize, int orgId, String type){
        String sqlExceptSelect = null;
        if(Broadband.BD_MARKET.equals(type)){
            // 大市场有多个type，所以要单独写。
            sqlExceptSelect = "from broadband where is_deleted = 0 and enabled = 1 and (business_type= 1 or business_type=3) and ( broad_type=? or broad_type=? )";
        } else{
            // 校园宽带，商务动力等，都只有一个type。
            sqlExceptSelect = "from broadband where is_deleted = 0 and enabled = 1 and (business_type= 1 or business_type=3) and broad_type=?";
        }

        String orgSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and org_id in " + orgSql;
        }

        logger.debug("sql = select * " + sqlExceptSelect);

        // 校园宽带
        if(Broadband.BD_CAMPUS.equals(type)){
            return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect, 3);
        } else if(Broadband.BD_MARKET.equals(type)){
            /********************** 大市场 **********************************************************************/
            // 成都，只能看成都的。不能看全省的。
            Record orgRecord = Db.findFirst("select CityCode from organization where id=?", orgId);
            if(orgRecord != null && (orgRecord.getInt(Organization.CITYCODE) == InterfaceUtil.getIdChengdu())){
                sqlExceptSelect += " and org_id != ?";

                logger.debug("sql = select * " + sqlExceptSelect);
                return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect, 0, 1, InterfaceUtil.getIdTop());
            }

            logger.debug("sql = select * " + sqlExceptSelect);
            // 成都以外的地市
            return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect, 0, 1);
        } else{
            // 商务动力
            return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect, 2);
        }

    }

    /**
     * @Title: getListByType
     * @Description:TODO
     * @param pageNumber
     * @param pageSize
     * @param orgId
     * @param bd_type
     * @return Page<Record>
     */
    public Page<Record> getListByType(int pageNumber, int pageSize, int orgId, String bd_type){
        String sqlExceptSelect = "from broadband where is_deleted = 0 and enabled = 1 and (business_type= 2 or business_type=3)";
        String orgSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and org_id in " + orgSql;
        }

        if(StrKit.notBlank(bd_type)){// 商务动力、校园
            sqlExceptSelect += " and broad_type=? ";
            logger.debug("sql = select * " + sqlExceptSelect);
            return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect, bd_type);
        } else{// 大市场
            sqlExceptSelect += " and broad_type!=2 and broad_type!=3 ";

            //// 成都不能看全省的套餐
            Record orgRecord = Db.findFirst("select CityCode from organization where id=?", orgId);
            if(orgRecord != null && (orgRecord.getInt(Organization.CITYCODE) == InterfaceUtil.getIdChengdu())){
                sqlExceptSelect += " and org_id != ?";

                logger.debug("sql = select * " + sqlExceptSelect);
                return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect, InterfaceUtil.getIdTop());
            }

            logger.debug("sql = select * " + sqlExceptSelect);
            // 成都以外的地市
            return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect);
        }
    }

    /**
     * @Title: getDetailByType
     * @Description:TODO
     * @param id
     * @param bd_type
     * @return Broadband
     */
    public Broadband getDetailByType(String id, String bd_type){
        String sql = "select * from broadband where is_deleted=0  and enabled = 1 and id=? ";
        if(StrKit.notBlank(bd_type)){// 商务动力、校园
            sql += " and broad_type=? ";
            logger.debug("sql = " + sql);
            return findFirst(sql, new Object[] { id, bd_type });
        } else{// 大市场
            sql += " and broad_type!=2 and broad_type!=3 ";
            logger.debug("sql = " + sql);
            return findFirst(sql, id);
        }
    }

    /**
     * @Title: getDetails
     * @Description:TODO
     * @param id
     * @param bd_type
     * @return Broadband
     */
    public Broadband getDetails(String id, String bd_type){
        String sql = "select * from broadband where is_deleted=0 and enabled = 1  and id=? and broad_type=? ";
        return findFirst(sql, new Object[] { id, bd_type });
    }

    /**
     * @Title: getBroadbandByActType
     * @Description:业务配置取校园宽带预约套餐数据
     * @return List<Record>
     */
    public List<Record> getBroadbandByActType(){
        int orgId = InterfaceUtil.getOrgId();
        // String orgSql = InterfaceUtil.getChlidOrgIdSql(orgId,
        // Constant.MAX_ORG_LEVEL, true);

        String sql = "SELECT * FROM broadband bd WHERE bd.business_type=2 AND bd.is_deleted=0 AND bd.enabled=1 AND bd.broad_type=3";

        /*
         * if(StrKit.notBlank(orgSql)){ sql += " AND bd.org_id IN " + orgSql; }
         */
        sql += " AND bd.org_id=" + orgId;// 熊诗言：只取当前机构的
        return Db.find(sql);
    }

    /**
     * 泛店员获取大市场宽带套餐数据，包括大市场宽带预约和大市场宽带开户
     * 
     * @param bdScope:适用范围，1为开户，2为预约
     * 
     * @Title: getBroadbandListForMarket
     * @Description:条件：有效 + 类型为优家或者爱家 + 适用范围取传入值或者开户和预约都适用的数据(business_type=3) +
     *                    只取自己机构的数据
     * @return List<Record>
     */
    public List<Record> getBroadbandListForMarket(int bdScope){
        int orgId = InterfaceUtil.getOrgId();
        String sql = "SELECT b.id,b.name FROM broadband b WHERE b.enabled=1 AND b.is_deleted=0 AND (b.broad_type=0 OR b.broad_type=1) AND (b.business_type=? OR b.business_type=3) AND b.org_id=?";

        return Db.find(sql, new Object[] { bdScope, orgId });
    }

    /**
     * @Title: getSqlExceptSelect
     * @Description:泛店员获取已授权列表时组装sql脚本
     * @param bdScope
     * @return String
     */
    public String getSqlExceptSelect(int bdScope){
        return "broadband bus_temp ON bac.config_business_id = bus_temp.id WHERE bus_temp.enabled=1 AND bus_temp.is_deleted=0 AND (bus_temp.broad_type=0 OR bus_temp.broad_type=1) AND (bus_temp.business_type="
                + bdScope + " OR bus_temp.business_type=3)";
    }
}
